from odoo import models, fields, api, _

from odoo.exceptions import UserError, ValidationError


class report_sb_crm_lead_view(models.AbstractModel):
    _name = 'report.sb_crm_ext.report_sb_crm_lead_view'
    _description = 'CRM Report'

    @api.model
    def _get_report_values(self, docids, data=None):
        report = self.env['ir.actions.report']._get_report_from_name(
            'sb_crm_ext.report_sb_crm_lead_view')

        docs = self.env['crm.lead'].browse(docids)
        if len(set(docs.mapped('partner_id'))) > 1:
            raise UserError(_('The selected leads must be for the same customer.'))
        remark_list = []
        ttl_freight = False
        tooling_cost = False
        material_lt = False
        nre_bool = False
        mov_bool = False
        for doc in docs:
            if doc.ttl_freight:
                ttl_freight = True
            if doc.tooling_cost:
                tooling_cost = True
            if doc.material_lt:
                material_lt = True
            if doc.nre_bool:
                nre_bool = True
            if doc.mov_bool:
                mov_bool = True
            remark = doc.remarks.replace('\n', '<br/>') if doc.remarks else ''
            remark_list.append(remark)

        return {
            'doc_model': report.model,
            'docs': docs,
            'data': data,
            'ttl_freight': ttl_freight,
            'tooling_cost': tooling_cost,
            'material_lt': material_lt,
            'mov_bool': mov_bool,
            'nre_bool': nre_bool,
            'remark_list': remark_list,
            'multi': True if len(docs) > 1 else False,
            'self': self
        }

    @api.model
    def strip_float_trailing_zeros(self, total_amount):
        if isinstance(total_amount, float):  # 如果是浮动数
            if total_amount.is_integer():  # 如果是整数形式的小数
                return str(int(total_amount))  # 转换成整数并返回
            else:
                return f"{total_amount:.3f}".rstrip('0').rstrip('.')  # 保留三位小数并去除尾随零
        else:
            return str(total_amount)  # 其他类型直接转换为字符串

    @api.model
    def get_uom_char(self, line):
        if line:
            uom_char = line._fields['uom_char'].convert_to_export(line.uom_char, line)
            return uom_char.upper()

    def get_uom_display(self, uom_key):
        """ 根据 uom_key 返回对应的显示名称 """
        uom_dict = {
            'day': 'Days',
            'month': 'WDs',
            'week': 'Weeks'
        }
        return uom_dict.get(uom_key, '')
